package com.liujun.spring4x.demo.dao;

import com.liujun.spring4x.demo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 进行用户数据操作的相关的接口的实现
 *
 * @author liujun
 * @date 2018-08-05 08:10:00
 * @version 1.0
 */
// 通过spring注解定义一个DAO
@Repository
public class UserDaoImpl implements UserDao {

  /** 数据库操作对象 */
  private JdbcTemplate jdbcTemplate;

  /** 进行用户登录的操作SQL */
  private static final String MATCH_COUNT_SQL =
      "select count(*) from t_user where user_name = ?  and `password` = ?";

  /** 进行修改相关操作的SQL */
  private static final String UPDATE_LOGIN_SQL =
      "update t_user set last_visit = ?,last_ip = ?,credits = ?  where user_id = ? ";

  /** 根据用户名查询相关的用户信息 */
  private static final String QUERY_BY_USERNAME =
      "select t.user_id,t.user_name,t.credits from t_user t where  t.user_name = ?";

  @Autowired // 自动注入JdbcTemplate的bean
  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  @Override
  public int getMatchCount(String userName, String password) {
    return jdbcTemplate.queryForObject(
        MATCH_COUNT_SQL, new Object[] {userName, password}, Integer.class);
  }

  /**
   * 根据用户名查询用户信息
   *
   * @param userName 用户名
   * @return 用户信息
   */
  @Override
  public User findUserByUserName(final String userName) {
    final User user = new User();
    jdbcTemplate.query(
        QUERY_BY_USERNAME,
        new Object[] {userName},
        // 进行匿名类方法实现的回调函数
        new RowCallbackHandler() {
          @Override
          public void processRow(ResultSet resultSet) throws SQLException {
            user.setUserId(resultSet.getInt("user_id"));
            user.setUserName(userName);
            user.setCredits(resultSet.getInt("credits"));
          }
        });
    return user;
  }

  /**
   * 修改用户的相关信息
   *
   * @param user 用户信息
   */
  @Override
  public void updateLoginInfo(User user) {
    jdbcTemplate.update(
        UPDATE_LOGIN_SQL,
        new Object[] {user.getLastVisit(), user.getLastIp(), user.getCredits(), user.getUserId()});
  }
}
